package com.aistar.controller;

import com.aistar.pojo.Address;
import com.aistar.service.AddressService;
import com.aistar.util.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @PostMapping("/add")
    @ResponseBody
    public ServerResponse addAddress(Address address){
        address.setAddressStatus(1);
        System.out.println("customerId:"+address.getCustomerId());
        System.out.println("地址名称："+address.getAddressName());
        System.out.println("省份："+address.getAddressProvince());
        //先判断该用户拥有几个地址
        ServerResponse serverResponse = addressService.getAddressCount(address.getCustomerId());
        Integer count = (Integer) serverResponse.getData();
        if (count>10){
            return ServerResponse.getDataFailed("您不可再创建地址");
        }else {

            return addressService.save(address);

        }

    }

    @GetMapping("/getAll/{customerId}")
    @ResponseBody
    public ServerResponse getAllAddress(@PathVariable("customerId") Integer customerId){
        ServerResponse serverResponse = addressService.getAllByCustomerId(customerId);
        if (serverResponse.getStatus()==1){
            List<Address> addressList = (List<Address>) serverResponse.getData();
            return ServerResponse.getDataSuccess(addressList);
        }else {
            return ServerResponse.getDataFailed("未查询该用户的地址");
        }

    }

    @GetMapping("/getCount/{customerId}")
    @ResponseBody
    public ServerResponse getCount(@PathVariable("customerId") Integer customerId){
        ServerResponse serverResponse =  addressService.getAddressCount(customerId);
            Integer count = (Integer) serverResponse.getData();
            return  ServerResponse.getDataSuccess(count);

   }
   @GetMapping("/delete/{addressId}")
   @ResponseBody
   public ServerResponse deleteAddress(@PathVariable("addressId") Integer addressId){
        //根据地址id 获取到地址对象
       ServerResponse serverResponse = addressService.getById(addressId);
       Address address = null;
       if (serverResponse.getStatus()==1){
           //获取到了地址列表
           List<Address> addressList = (List<Address>) serverResponse.getData();
            address = addressList.get(0);

       }
       return  addressService.modifyStatus(address);

   }
}
